// hooks 封装逻辑，提供响应式数据
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { ref, onUnmounted } from 'vue'
import dayjs from 'dayjs'

// 数据懒加载函数
export const useLazyData = apiFun => {
  // 需要
  // 1.被观察的dom节点
  // 2.不同的api函数
  const target = ref(null)
  const result = ref([])

  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop()
        // 调用apiFun获取数据
        apiFun().then(data => {
          result.value = data.result
        })
      }
    },
    {
      threshold: 0
    }
  )

  // 返回数据(dom、后台数据)
  return {
    target,
    result
  }
}

/**
 * 支付倒计时
 */
export const usePayTime = () => {
  // 倒计时逻辑
  const time = ref(0)
  const timeText = ref('')

  const { pause, resume } = useIntervalFn(
    () => {
      /* your function */
      time.value--
      timeText.value = dayjs.unix(time.value).format('mm分ss秒')
      if (time.value <= 0) {
        pause()
      }
    },
    1000,
    false
  )

  onUnmounted(() => {
    pause()
  })

  // 开启定时器 countdown 倒计时
  const start = countdown => {
    time.value = countdown
    timeText.value = dayjs.unix(time.value).format('mm分ss秒')

    resume()
  }

  return {
    timeText,
    start
  }
}
